/**
 * 群发页面
 */
;(function(g){

  if (g.wxMassSend) return false;

  var mass = g.wxMassSend = { };

  /**
   * 属性区
   */

  // 消息类型
  // {text: '文字',acl: "can_text_msg",className: "tab_text",selector: "js_textArea",innerClassName: "no_extra",type: 1},
  // {text: '图片',acl: "can_image_msg",className: "tab_img",selector: "js_imgArea",type: 2},
  // {text: '语音',acl: "can_voice_msg",className: "tab_audio",selector: "js_audioArea",type: 3},
  // {text: '视频',acl: "can_video_msg",className: "tab_video",selector: "js_videoArea",type: 4},
  // {text: '图文消息',acl: "can_app_msg",className: "tab_appmsg",selector: "js_appmsgArea",type: 10},
  // {text: '商品消息',acl: "can_commodity_app_msg",className: "tab_commondity_appmsg",selector: "js_commondityAppmsgArea",type: 11}
  mass.types = {
    1: '文字',
    2: '图片',
    3: '语音',
    4: '视频',
    10: '图文消息',
    11: '商品消息'
  };


  /*
    1. 文本
      type:1
      content:/发呆fawefawfaw哈哈哈fawef/得意
      tofakeid:2681469461
      imgcode:
      token:686188177
      lang:zh_CN
      random:0.32573492266237736
      t:ajax-response

    2. 图片、语音、视频
      type:2
      file_id:10000000
      tofakeid:2681469461
      fileid:10000000
      imgcode:
      token:686188177
      lang:zh_CN
      random:0.6631580910179764
      t:ajax-response

    3. 图文
      type:10
      app_id:10000001
      //tofakeid:2681469461
      appmsgid:10000001
      //imgcode:
      //token:686188177
      //lang:zh_CN
      //random:0.6052857046015561
      //t:ajax-response
  */
  mass.message = {
    tofakeid: 0,
    random  : Math.random(),
    imgcode : '',
    lang    : 'zh_CN',
    t       : 'ajax-response',
    token   : wxqf_common.getToken()
  };


  /**
   * 是否还有剩余待发的消息
   */
  mass.getLeftNum = function()
  {
    var obj = $('.mass_send_tips #leftNum');
    if (obj.length) return parseInt(obj.text());
    return 0;
  };

  /**
   * 获取输入框的文本
   */
  mass.getTextContent = function()
  {
    var html = $('.js_editorArea[contenteditable="true"]').html();
    if (!$('#wxqfzs_content_box').length) {
      $('body').append('<div id="wxqfzs_content_box" style="display:none;"></div>');
    }
    $('#wxqfzs_content_box').html(html);

    // 替换图片
    $.each($('#wxqfzs_content_box img'), function(){
      var parse = $(this).attr('alt').replace('mo-', '/');
      $(this).after(parse);
    });

    return $('#wxqfzs_content_box').text();
  };

  /**
   * 修改dom
   */
  mass.resetDom = function()
  {
    var leftNum = this.getLeftNum();

    // 如果还有发送名额，则不修改
    if (leftNum && !confirm("你今天还能使用微信官方群发 "+leftNum+" 条消息，确定要使用群发助手吗？")) {
      if (g.wxqf_common.DEBUG) console.log("mass.resetDom: leftNum > 0");
      return this;
    }

    // 地区隐藏
    $('#js_region').hide();
    // 性别隐藏
    $('#js_sex').closest('.send_group').hide();
    // 插入群发按钮
    $('#js_submit').closest("span").removeClass('btn_disabled').html('<button id="wxqfzsSendBtn">用群发助手发送</button>');

    return this;
  };

  /**
   * 绑定按钮事件
   * @return {[type]} [description]
   */
  mass.bindBtnEvent = function()
  {
    var me = this;

    // 群发收集消息
    $('#wxqfzsSendBtn').bind('click', function(){

      // 获取selected的消息类型
      var type = parseInt($('#js_msgSender .tab_nav.selected').attr('data-type'));
      if(isNaN(type)) {
        alert('请选择群发发送的消息类型');
        return false;
      }
      me.message.type = type;

      // 获取发送分组
      var groupid;
      if ($('#js_group:visible').length) {
        var groupName = $('#js_group:visible').children('.jsDropdownBt').text().trim();
        groupid = parseInt($('#js_group .jsDropdownItem[data-name="'+groupName+'"]').attr('data-value'));
      }

      // 如果是文本消息
      if(type == 1) {
        delete me.message.file_id;
        delete me.message.fileid;
        delete me.message.appmsgid;
        delete me.message.app_id;
        // 获取文本消息
        var content = me.getTextContent();
        if (!content || content.length > 600) {
          alert('发送的文本消息字数必须在1~600之间');
          return false;
        }
        me.message.content = content;
      } else {
        var box =  $('#js_msgSender .tab_content:visible');
        if(!box.length) {
          alert('获取待发送的多媒体消息失败[1]');
          return false;
        }
      }
      if (type == 2 || type == 3 || type == 4) {
        // appmsgid
        delete me.message.content;
        delete me.message.appmsgid;
        delete me.message.app_id;

        var mediaId;
        if (type == 2) {
          var tmpUrl    = box.find('.media_img').attr('href');
          var tmpUrlArr = wxqf_common.parseUrl(tmpUrl);
          mediaId = tmpUrlArr && tmpUrlArr.queryParams.fileId ? tmpUrlArr.queryParams.fileId : null;
        } else if (type == 3) {
          mediaId = box.find('#wxAudioBox').attr('data-fid');
        } else if (type == 4) {
          mediaId = box.find('.wxVideoScreenshot').attr('data-vid');
        }
        mediaId = parseInt(mediaId);
        if (!mediaId) {
          alert('获取待发送的多媒体消息失败[2]');
          return false;
        }
        me.message.fileid = mediaId;
        me.message.file_id = mediaId;
      }
      else if (type == 10) {
        // appmsgid
        delete me.message.content;
        delete me.message.fileid;
        delete me.message.file_id;

        var appmsgid = parseInt(box.find('.appmsg').attr('data-id'));
        if (!appmsgid) {
          alert('获取待发送的多媒体消息失败[3]');
          return false;
        }
        me.message.appmsgid = appmsgid;
        me.message.app_id   = appmsgid;
      }

      if (wxqf_common.DEBUG) console.log('mass.message: ', me.message);

      if(!confirm('确定要群发这条消息？')) {
        return false;
      }

      // 发送数据
      var data = {
        groupid     : groupid,
        message     : me.message,
        messageHtml : $('#js_msgSender .tab_panel').html()
      };

      // 添加任务
      wxqf_common.api('messageAddTask', data, function(ret){
        if(ret.result == true) {
          // 跳转到用户页面
          var url = wxqf_common.getPageUrl('user', wxqf_common.getToken());
          window.location.href = url + '#wxqfzs_send';
        } else {
          alert(ret.error);
        }
      });

    });

    return this;
  };

})(window);




$(function(){

  wxqf_common.api('getBindWeixinName', {}, function(ret){
    if (!ret.result) return false;
    var wxName = wxqf_common.getWeixinName();
    if (wxName == ret.data) {
      // 重置dom树
      wxMassSend.resetDom().bindBtnEvent();
    }
  });


});